/* 采购 */
const express = require("express");
const router = express.Router();
const fs = require('fs')
const path = require('path')
var mysql = require("mysql");
var multer = require('multer')
const { noticePath } = require('../url')
console.log(noticePath, 'nowPath')
const env = {
    host: "111.231.22.97",
    user: "wangs-web",
    password: "HsTjw82zF7f6fjWY",
    database: "wangs-web", //数据库名字
    multipleStatements: true //允许多条sql语句查询
};



//新增id
const indexs = () => {
    let str = "";
    for (let i = 0; i < 10; i++) {
        let ind = Math.ceil(Math.random() * 10);
        str += ind + 1;
    }
    return str;
};

const url = path.join(__dirname, '/file')


/* 新增 */
const postBuylist = (req, res) => {
    let pools = mysql.createPool(env)
    let sql = 'insert into buylist values (?,?,?,?,?,?,?,?)'
    const { title, content, buyPrice, buyDate, buyURL, author } = req.body
    let queryArr = [indexs(), title, content, buyPrice, buyDate, buyURL, author, '0']
    pools.query(sql, queryArr, (err, resk) => {
        try {
            if (resk.affectedRows >= 1) {
                res.send({
                    code: 200,
                    msg: 'success'
                })
            }
            else {
                res.send({
                    code: 500,
                    msg: 'error'
                })
            }
        } catch {
            res.status(500)
            console.log(err, 'error')
        }
    })
}
router.post('/postBuylist', (req, res) => {
    postBuylist(req, res)
})




/* 上传文件(多文件上传) */
const storage = multer.diskStorage({
    destination: (req, file, cb) => {
        cb(null, url);
    },
    filename: (req, file, cb) => {
        file.originalname = Buffer.from(file.originalname, "latin1").toString(
            "utf-8"
        );
        cb(null, file.originalname);
    }
});
const upload = multer({ storage: storage });
router.post('/postMoreFile', upload.array('file'), (req, res) => {
    if (req.files) {
        res.send({
            code: 200,
            msg: 'success',
            data: {
                name: req.files[0].originalname
            }
        })
    }
})


//过滤
const filters = (e) => {
    let objs = {};
    for (let keys in e) {
        if (e[keys] != "" && e[keys] != undefined && e[keys] != null) {
            objs[keys] = e[keys];
        }
    }
    return Object.keys(objs);
};




//获取列表信息
const getPurchaseList = (req, res) => {
    let pools = mysql.createPool(env)
    let start = (Number(req.query.pageNo) - 1) * Number(req.query.pageSize)
    let end = Number(req.query.pageNo) * Number(req.query.pageSize)
    let arrs = filters(req.query)
    if (arrs.length == 2) {
        let sql = 'select * from buylist ORDER BY buyDate DESC;select count(*) from buylist'
        pools.query(sql, [], (err, result) => {
            if (err) {
                res.status(500)
                console.log(err, 'error')
            }
            let resData = result[0].slice(start, end)
            res.send({
                code: 200,
                msg: 'success',
                data: {
                    data: resData,
                    total: result[1][0]['count(*)']
                }
            })
        })
    }
    else {
        let pools = mysql.createPool(env)
        let target = filters(req.query).filter(res => { return res != 'pageSize' && res != 'pageNo' })
        let queryArr = []
        let sql = 'select * from buylist  where  '
        target.forEach((ele, index) => {
            queryArr.push(req.query[ele]);
            if (index != target.length - 1) {
                sql += ` ${ele} = ? and `
            }
            else {
                sql += ` ${ele} = ? ORDER BY buyDate DESC `
            }
        })
        console.log(queryArr, 'ooo')
        pools.query(sql, queryArr, (err, resk) => {
            try {
                if (resk.length > 0) {
                    res.send({
                        code: 200,
                        msg: 'success',
                        data: {
                            data: resk.slice(start, end),
                            total: resk.length
                        }
                    })
                }
                else if (resk.length == 0) {
                    res.send({
                        code: 200,
                        msg: 'success',
                        data: {
                            data: [],
                            total: 0
                        }
                    })
                }
                else {
                    res.send({
                        code: 500,
                        msg: 'error'
                    })
                }
            } catch {
                console.log(err)
                res.status(500)
            }
        })
    }
}
router.get('/getPurchaseList', (req, res) => {
    getPurchaseList(req, res)
})

//根据id获取详细信息
const getPurchaseDetail = (req, res) => {
    let pools = mysql.createPool(env)
    const { id } = req.body
    let sql = 'select * from buylist where id = ?'
    let queryArr = [id]
    pools.query(sql, queryArr, (err, resl) => {
        if (err) {
            res.status(500)
            console.log(err)
        }
        else {
            if (resl.length > 0) {
                res.send({
                    code: 200,
                    msg: 'success',
                    data: {
                        data: resl[0],
                    }
                })
            }
            else {
                res.send({
                    code: 500,
                    msg: '查无此数据'
                })
            }
        }
    })
}
router.post('/getPurchaseDetail', (req, res) => {
    getPurchaseDetail(req, res)
})



//修改详情
//过滤掉的字段
const filterArrs = (e, k) => {
    let arr = e.filter(res => { return !k.includes(res) })
    return arr
}

const updatePurchase = (req, res) => {
    let sql = 'update buylist set '
    let keys = Object.keys(req.body)
    let arrs = ['buyURL', 'status', 'author', 'id']
    let target = filterArrs(keys, arrs)
    //过滤掉
    let queryArr = []
    target.forEach((ele, ind) => {
        queryArr.push(req.body[ele])
        if (ind != target.length - 1) {
            sql += ` ${ele} = ? ,`
        }
        else {
            sql += ` ${ele} = ? where id = ?`
        }
    })
    //引用pools
    queryArr.push(req.body['id'])
    let pools = mysql.createPool(env)
    pools.query(sql, queryArr, (err, result) => {
        try {
            if (result.affectedRows >= 0) {
                res.send({
                    code: 200,
                    msg: 'success'
                })
            }
        } catch {
            res.status(500)
            console.log(err, 'error')
        }
    })
}
router.post('/updatePurchase', (req, res) => {
    updatePurchase(req, res)
})



//发布
//查询
const selectById = (id) => {
    return new Promise((resolve, reject) => {
        let sql = 'select * from buylist where id = ?'
        let pools = mysql.createPool(env)
        let queryArr = [id]
        pools.query(sql, queryArr, (err, result) => {
            try {
                resolve(result[0])
            } catch {
                res.status(500)
                console.log(err, 'error')
            }
        })
    })
}
//存数据到表里
const save = (req, res, obj, url, str) => {
    let pools = mysql.createPool(env)
    let sql = 'insert into noticelist values(?,?,?,?,?,?);delete from buylist where id = ?'
    const { id, title, author, buyDate } = obj
    let queryArr = [id, title, author, buyDate, url, '0', id]
    pools.query(sql, queryArr, (err, result) => {
        try {
            let deter = result.every(el => { return el.affectedRows >= 1 })
            if (deter) {
                //写入
                fs.writeFile(url, str, 'utf-8', (err) => {
                    if (err) {
                        res.status(500)
                        console.log(err, 'error')
                    }
                    else {
                        res.send({
                            code: 200,
                            msg: 'success'
                        })
                    }
                })
            }
        } catch {
            res.status(500)
            console.log(err)
        }
    })
}


const publicPurchase = async (req, res) => {
    //根据id查询
    const { id } = req.body
    let pools = mysql.createPool(env)
    pools.query('select * from buylist where id = ?', [id], async (err, result) => {
        if (err) {
            res.status(500)
            console.log(err)
        }
        else {
            //文件地址
            if (result.length > 0) {
                let filename = 'ws' + new Date().getTime()
                let url = noticePath + `${filename}.txt`
                let str = `<h2 style="width:100%;text-align:center;font-weight:bold;">${result[0].title}</h2><p style="text-indent:24px;padding:10px 0;">${result[0].content}</p>`
                save(req, res, result[0], url, str)
            }
            else {
                res.send({
                    code: 500,
                    msg: '数据不存在'
                })
                return
            }
        }
    })
}
router.post('/publicPurchase', (req, res) => {
    publicPurchase(req, res)
})

module.exports = router;